package account

import (
	"context"

	v1 "myapp/api/account/v1"
	"myapp/internal/service"

	"github.com/gogf/gf/v2/errors/gerror"
)

func (c *ControllerV1) Detail(ctx context.Context, req *v1.DetailReq) (res *v1.DetailRes, err error) {
	user, err := service.Member().Detail(ctx)
	if err != nil {
		return nil, err
	}
	return &v1.DetailRes{
		Username:     user.Username,
		Roles:        []string{"admin"},
		Introduction: "I am an admin",
		Avatar:       "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif",
		Name:         user.Nickname,
	}, nil
}
func (c *ControllerV1) RefreshToken(ctx context.Context, req *v1.RefreshTokenReq) (res *v1.RefreshTokenRes, err error) {
	//1. 解析token
	serv := service.JwtToken()
	claims, err := serv.ParseToken(ctx, req.Token)
	if err != nil {
		return nil, err
	}

	//2. 验证token
	ctxUser := service.CustomContext().GetContextUser(ctx)
	if ctxUser == nil {
		return nil, gerror.New("未找到登陆的信息")
	}
	if ctxUser.Id != claims.Id {
		return nil, gerror.New("header token与提交的token不一致")
	}

	//3. 重新生成token
	token, err := serv.CreateToken(ctx, claims.Id, claims.Username)
	if err != nil {
		return nil, err
	}

	return &v1.RefreshTokenRes{Token: token}, nil
}
